package org.unt.logic;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sun.org.apache.xalan.internal.xsltc.compiler.util.NodeType;

public class DOMLogic {

	public static void main(String[] args) {
		new DOMLogic("E:/java/test/pom.xml").read();
	}

	private Document dom;

	public DOMLogic(String absolutePathXML) {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;

		try {

			db = dbf.newDocumentBuilder();

		} catch (ParserConfigurationException e) {
			throw new RuntimeException("ParserConfigurationException: Cannot create DocumentBuilder", e);
		}

		try {

			dom = db.parse(absolutePathXML);

		} catch (SAXException e) {
			throw new RuntimeException("SAXException: Cannot parse file " + absolutePathXML, e);
		} catch (IOException e) {
			throw new RuntimeException("IOException: Cannot parse file " + absolutePathXML, e);
		}
	}

	public void read() {

		Element docEle = dom.getDocumentElement();

		NodeList nodeList = docEle.getElementsByTagName("artifactId");

		if (nodeList != null && nodeList.getLength() > 0) {

			for (int i = 0; i < nodeList.getLength(); i++) {

				if ("maven-checkstyle-plugin".equals(nodeList.item(i).getTextContent())) {

					// System.out.println(
					// nodeList.item(i).getParentNode().getNodeName());

					NodeList childs = nodeList.item(i).getParentNode().getChildNodes();

					for (int j = 0; j < childs.getLength(); j++) {

						if (childs.item(j).getNodeType() == Node.ELEMENT_NODE) {

							// }
							// System.out.println(childs.item(j).getNodeType()
							// == NodeType.Element);

							System.out.println(childs.item(j).getNodeName() + " " + childs.item(j).getTextContent());
						}
					}

					// System.out.println(nodeList.item(i).getNodeName() + " " +
					// nodeList.item(i).getTextContent());
				}
			}
		}
	}
}
